<template>
    <div class="basic-info">
        <div class="component-title">
            <h3>商品基本信息</h3>
        </div>

        <el-form :model="form" label-width="120px" ref="basicForm" :rules="rules">
            <!-- 基本信息部分 -->
            <div class="form-section">
                <div class="section-title">
                    <i class="el-icon-info"></i>
                    <span>基本信息</span>
                </div>

                <el-form-item label="商品名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入商品名称"></el-input>
                </el-form-item>

                <el-form-item label="商品分类" prop="category_id">
                    <el-cascader v-model="form.category_id" :options="categoryOptions"
                        :props="{ expandTrigger: 'hover' }" placeholder="请选择商品分类"
                        @change="handleCategoryChange"></el-cascader>
                </el-form-item>

                <el-form-item label="品牌" prop="brand_id">
                    <el-select v-model="form.brand_id" placeholder="请选择品牌">
                        <el-option v-for="item in brandOptions" :key="item.id" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="运费模板" prop="shipping_template_id">
                    <el-select v-model="form.shipping_template_id" placeholder="请选择运费模板">
                        <el-option v-for="item in shippingTemplateOptions" :key="item.id" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="商品状态" prop="status">
                    <el-radio-group v-model="form.status">
                        <el-radio :label="1">上架</el-radio>
                        <el-radio :label="0">下架</el-radio>
                        <el-radio :label="2">审核中</el-radio>
                    </el-radio-group>
                </el-form-item>
            </div>

            <!-- 图片与视频部分 -->
            <div class="form-section">
                <div class="section-title">
                    <i class="el-icon-picture"></i>
                    <span>图片与视频</span>
                </div>

                <el-form-item label="商品主图" prop="main_image">
                    <el-upload action="#" :auto-upload="false" :on-change="handleMainImageChange"
                        :file-list="form.main_image_list" :limit="1" list-type="picture-card">
                        <i class="el-icon-plus"></i>
                        <div slot="tip" class="el-upload__tip">建议尺寸：800x800像素，支持JPG、PNG格式</div>
                    </el-upload>
                </el-form-item>

                <el-form-item label="商品图册" prop="album_images">
                    <el-upload action="#" :auto-upload="false" :on-change="handleAlbumImagesChange"
                        :file-list="form.album_images_list" multiple list-type="picture-card" :limit="5">
                        <i class="el-icon-plus"></i>
                        <div slot="tip" class="el-upload__tip">最多可上传5张图片</div>
                    </el-upload>
                </el-form-item>

                <el-form-item label="商品视频" prop="video">
                    <el-upload action="#" :auto-upload="false" :on-change="handleVideoChange"
                        :file-list="form.video_list" :limit="1" accept=".mp4,.mov">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">支持mp4格式，大小不超过10MB</div>
                    </el-upload>
                </el-form-item>
            </div>

            <!-- 描述与详情部分 -->
            <div class="form-section">
                <div class="section-title">
                    <i class="el-icon-document"></i>
                    <span>描述与详情</span>
                </div>

                <el-form-item label="商品描述" prop="description">
                    <el-input type="textarea" v-model="form.description" placeholder="请输入商品简要描述" :rows="3"></el-input>
                </el-form-item>

                <el-form-item label="商品详情" prop="detail">
                    <el-input type="textarea" v-model="form.detail" placeholder="请输入商品详细描述" :rows="5"></el-input>
                </el-form-item>

                <el-form-item label="详细页标题" prop="detail_title">
                    <el-input v-model="form.detail_title" placeholder="请输入详细页标题"></el-input>
                </el-form-item>

                <el-form-item label="详细页描述" prop="detail_desc">
                    <el-input type="textarea" v-model="form.detail_desc" placeholder="请输入详细页描述" :rows="2"></el-input>
                </el-form-item>

                <el-form-item label="商品关键字" prop="keywords">
                    <el-input v-model="form.keywords" placeholder="请输入商品关键字，多个关键字用逗号分隔"></el-input>
                </el-form-item>

                <el-form-item label="商品备注" prop="note">
                    <el-input type="textarea" v-model="form.note" placeholder="请输入商品备注（仅内部可见）" :rows="2"></el-input>
                </el-form-item>
            </div>

            <!-- 积分与服务部分 -->
            <div class="form-section">
                <div class="section-title">
                    <i class="el-icon-medal"></i>
                    <span>积分与服务</span>
                </div>

                <el-form-item label="赠送积分" prop="points">
                    <el-input v-model="form.points" placeholder="0"></el-input>
                </el-form-item>

                <el-form-item label="赠送成长值" prop="growth_value">
                    <el-input v-model="form.growth_value" placeholder="0"></el-input>
                </el-form-item>

                <el-form-item label="积分购买限制" prop="point_limit">
                    <el-input v-model="form.point_limit" placeholder="0"></el-input>
                </el-form-item>

                <el-form-item label="预告商品" prop="is_preview">
                    <el-switch v-model="form.is_preview"></el-switch>
                </el-form-item>

                <el-form-item label="商品上架" prop="is_publish">
                    <el-switch v-model="form.is_publish"></el-switch>
                </el-form-item>

                <el-form-item label="商品推荐" prop="recommends">
                    <div class="recommend-options">
                        <div class="recommend-item">
                            <span>新品</span>
                            <el-switch v-model="form.is_new"></el-switch>
                        </div>
                        <div class="recommend-item">
                            <span>推荐</span>
                            <el-switch v-model="form.is_recommend"></el-switch>
                        </div>
                    </div>
                </el-form-item>

                <el-form-item label="服务保证" prop="services">
                    <el-checkbox-group v-model="form.services">
                        <el-checkbox label="无忧退货">无忧退货</el-checkbox>
                        <el-checkbox label="快速退款">快速退款</el-checkbox>
                        <el-checkbox label="免费包邮">免费包邮</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </div>
        </el-form>
    </div>
</template>

<script>
import { debounce } from 'lodash-es';

export default {
    name: 'BasicInfo',
    props: {
        formData: {
            type: Object,
            required: true
        },
        categoryOptions: {
            type: Array,
            default: () => []
        },
        brandOptions: {
            type: Array,
            default: () => []
        },
        shippingTemplateOptions: {
            type: Array,
            default: () => []
        }
    },
    data() {
        return {
            form: { ...this.formData },
            rules: {
                name: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
                ],
                category_id: [
                    { required: true, message: '请选择商品分类', trigger: 'change' }
                ]
            },
            imageCache: {} // 添加图片缓存对象
        };
    },
    watch: {
        formData: {
            handler(val) {
                // 避免不必要的深层更新
                const needUpdate = JSON.stringify(this.form) !== JSON.stringify(val);
                if (needUpdate) {
                    this.form = { ...val };
                }
            },
            deep: true
        },
        form: {
            handler(val) {
                this.debouncedEmitUpdate(val);
            },
            deep: true
        }
    },
    created() {
        // 创建防抖函数
        this.debouncedEmitUpdate = debounce(this.emitUpdate, 300);
    },
    beforeDestroy() {
        // 清理图片资源
        this.releaseImageResources();

        // 取消防抖函数
        if (this.debouncedEmitUpdate && this.debouncedEmitUpdate.cancel) {
            this.debouncedEmitUpdate.cancel();
        }
    },
    methods: {
        emitUpdate(val) {
            this.$emit('update-form', val);
        },
        handleCategoryChange(value) {
            // 当分类变化时，可以触发一些操作，比如获取该分类下的属性
            this.$emit('category-change', value);
        },
        handleMainImageChange(file) {
            // 优化图片处理
            if (file.raw && file.raw.size > 5 * 1024 * 1024) {
                this.$message.warning('图片大小不能超过5MB');
                return;
            }

            this.form.main_image = file.raw;
            this.form.main_image_list = [file];
        },
        handleAlbumImagesChange(file, fileList) {
            // 优化图片处理
            const isLt5M = file.raw.size <= 5 * 1024 * 1024;
            if (!isLt5M) {
                this.$message.warning('图片大小不能超过5MB');
                return;
            }

            // 限制图片数量
            const limitedFileList = fileList.slice(0, 5);
            this.form.album_images = limitedFileList.map(item => item.raw);
            this.form.album_images_list = limitedFileList;
        },
        handleVideoChange(file) {
            // 优化视频处理
            if (file.raw && file.raw.size > 10 * 1024 * 1024) {
                this.$message.warning('视频大小不能超过10MB');
                return;
            }

            this.form.video = file.raw;
            this.form.video_list = [file];
        },
        releaseImageResources() {
            // 释放所有创建的对象URL，避免内存泄漏
            Object.values(this.imageCache).forEach(url => {
                try {
                    URL.revokeObjectURL(url);
                } catch (e) {
                    // 忽略错误
                }
            });
            // 清空缓存
            this.imageCache = {};
        },
        validate() {
            return new Promise((resolve, reject) => {
                this.$refs.basicForm.validate(valid => {
                    if (valid) {
                        resolve(true);
                    } else {
                        reject(new Error('基本信息验证失败'));
                    }
                });
            });
        }
    }
};
</script>

<style scoped>
.basic-info {
    padding: 20px;
}

.component-title {
    margin-bottom: 20px;
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
}

.component-title h3 {
    font-size: 18px;
    font-weight: 600;
    color: #333;
}

.form-section {
    margin-bottom: 30px;
    background: #f9f9f9;
    padding: 20px;
    border-radius: 4px;
}

.section-title {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

.section-title i {
    margin-right: 8px;
    color: #409EFF;
}

.recommend-options {
    display: flex;
    gap: 20px;
}

.recommend-item {
    display: flex;
    align-items: center;
    gap: 10px;
}
</style>